var isRepeat = false;
userName.onblur = async function () {
  // 失去焦点
  var loginId = userName.value.trim();
  if (!loginId) return;
  var response = await fetch(
    `https://study.duyiedu.com/api/user/exists?loginId=${loginId}`
  );
  var result = await response.json();
  console.log(result);
  // result.data为true的时候，表示已经存在此用户名
  isRepeat = result.data;
  if (isRepeat) {
    alert("该账号已存在，请更换用户名");
  }
};
formContainer.onsubmit = function (e) {
  // 表单提交事件
  e.preventDefault();
  var loginId = userName.value.trim();
  var nickname = userNickname.value;
  var loginPwd = userPassword.value.trim();
  var surePwd = userConfirmPassword.value.trim();
  // 表单验证
  var checkFormRes = checkForm(loginId, loginPwd, surePwd);
  if (!checkFormRes) {
    return;
  }
  // 数据请求
  sendData(loginId, nickname, loginPwd);
};
// 请求数据函数
var sendData = async function (loginId, nickname, loginPwd) {
  var res = await fetch("https://study.duyiedu.com/api/user/reg", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      loginId,
      nickname,
      loginPwd,
    }),
  });
  var token = res.headers.get("Authorization");
  // 存储token值,前面token有值就执行后面的代码
  token && (sessionStorage.token = token);
  sessionStorage.token &&
    (sessionStorage.Authorization = "Bearer" + " " + sessionStorage.token);

  var result = await res.json();
  if (result.code !== 0) {
    alert(result.msg);
  }
  location.href = `../login.html`;
};
// 验证表单函数
var checkForm = function (loginId, loginPwd, surePwd) {
  switch (true) {
    case !loginId:
      alert("用户名不能为空");
      return;
    case !loginPwd:
      alert("密码不能为空");
      return;
    case surePwd !== loginPwd:
      alert("两次输入的密码不一致");
      return;
    case isRepeat:
      alert("该账号已存在，请更换用户名");
      return;
    default:
      return true;
  }
};
